﻿using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Profile;
using System.Data;
using System.Text;

using Gift.DAL;
using Gift.Model;
using Gift.Model.ENUM;

namespace WebSite.admin.order
{
    public partial class orderprocess : BaseAdmin
    {



        protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.GridView1.PageIndex = this.ddlCurrentPage.SelectedIndex;
            this.GridViewBind("");
        }

        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if ((e.Row.RowType == DataControlRowType.Header) || (e.Row.RowType == DataControlRowType.DataRow))
            {
                CheckBox box = new CheckBox();
                box = (CheckBox)e.Row.FindControl("CheckBox1");
                if (box != null)
                {
                    if (e.Row.RowType == DataControlRowType.DataRow)
                    {
                        e.Row.Cells[1].Width = 80;
                        DataTable table = SQLAccess.GreatDs("select payname from DB_Pay where pay in (" + e.Row.Cells[4].Text + ") group by payname").Tables[0];
                        if (table.Rows.Count > 0)
                        {
                            e.Row.Cells[4].Text = table.Rows[0][0].ToString();
                        }
                        else
                        {
                            e.Row.Cells[4].Text = string.Empty;
                        }
                        foreach (DataRow dr in table.Rows)
                        {
                            e.Row.Cells[4].Text = e.Row.Cells[3].Text != "" ? e.Row.Cells[4].Text + ";" + dr[0].ToString() : dr[0].ToString();
                        }
                        e.Row.Cells[5].Text = info.info1("", "shophuobi") + string.Format("{0:f}", Convert.ToSingle(e.Row.Cells[5].Text)) + " 元";
                        if (e.Row.Cells[8].Text.ToString() == "0")
                        {
                            e.Row.Cells[8].Text = "新订单";
                        }
                        if (e.Row.Cells[8].Text.ToString() == "1")
                        {
                            e.Row.Cells[8].Text = "备货中";
                        }
                        if (e.Row.Cells[8].Text.ToString() == "2")
                        {
                            e.Row.Cells[8].Text = "已发货";
                        }
                        if (e.Row.Cells[8].Text.ToString() == "3")
                        {
                            e.Row.Cells[8].Text = "已完成";
                        }
                        e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=\"" + e.Row.Style["BACKGROUND-COLOR"] + "\"");
                        e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor=\"#efefef\"");
                    }
                    else if (e.Row.RowType == DataControlRowType.Header)
                    {
                        box.Attributes.Add("onclick", "SelectAll(this.checked)");
                    }
                    e.Row.Cells[9].Visible = false;
                }
            }
        }

        protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
        {
            string sqlsort = "";
            sqlsort = "select *,(select isnull(sum(sumprice),0) from DB_Car where orderid=o.orderid)  as sumprice from DB_order o where languages=" + info.languages("") + " ";

            sqlsort = sqlsort + GetSql();
            this.GridViewBind(sqlsort);
        }

        private string GetSql()
        {
            string sql = "";
            if (this.ordercode.Value != "")
            {
                sql = sql + " and o.ordercode like '%" + this.ordercode.Value.ToString() + "%'";
            }
            if (this.product.Value != "")
            {
                sql = sql + " and o.orderid in(select orderid from DB_Car c join DB_Shoppro s on c.productid = s.proid  where s.proname like '%" + this.product.Value.ToString() + "%') ";
            }
            if (this.states.Value != "")
            {
                sql = sql + " and o.states=" + this.states.Value.ToString() + " ";
            }
            //if (this.spec.Value != "")
            //{
            //   sql = sql + " and o.orderid in(select orderid from DB_Car  where contents like '%" + this.product.Value.ToString() + "%') ";
            //}
            if (this.sendDateFrom.Value != "")
            {
                sql = sql + " and (o.sendDate >= '" + this.sendDateFrom.Value + "' or o.sendDate is null)";
            }
            if (this.sendDateTo.Value != "")
            {
                sql = sql + " and (o.sendDate <= '" + this.sendDateTo.Value + " 23:59' or o.sendDate is null)";
            }
            //---
             if (this.ddlProductType.SelectedItem.Value == "0")
             {
                 if (this.ddlProfessionAreaType.SelectedItem.Value != "")
                {
                      sql = sql + " and o.orderid in(select orderid from DB_Car c join DB_Shoppro s on c.productid = s.proid   where s.ProfessionAreaTypeId=" + this.ddlProfessionAreaType.SelectedItem.Value + ") ";
                 }
            }
             else if (this.ddlProductType.SelectedItem.Value == "1")
             {

                 sql = sql + " and o.orderid in(select orderid from DB_Car c join DB_Shoppro s on c.productid = s.proid   where s.proisnew4=1) ";
             }
                 //--
            
           
            return sql;
        }

        private void GridViewBind(string Sqlsort)
        {
            string sql = "select orderid, ordercode, memberid, pay, ship, cname, tel, phone, post, address, email, [content], cname1, tel1, phone1, post1, address1, email1, content1, states, "
                     + " ordertime, paytime, shiptime, languages, totalprice, cardprice, scoreprice, orderscore, cardid, scoretype, SendCompany, SendCode, convert(varchar(10),senddate,111) as senddate, senddate1 "
                     + " ,(select isnull(sum(sumprice),0) from DB_Car where orderid=o.orderid)  as sumprice from DB_order o where languages=" + info.languages("") + " ";


            sql = sql + GetSql();

            sql = sql + " order by o.ordertime desc";

            DataTable table = new DataTable();
            table = SQLAccess.GreatDs(sql).Tables[0];
            this.GridView1.DataSource = table.DefaultView;
            this.GridView1.DataBind();
            this.LblCurrentIndex.Text = "当前第 " + ((this.GridView1.PageIndex + 1)).ToString() + "页";
            this.LblPageCount.Text = "共 " + this.GridView1.PageCount.ToString() + "页";
            this.LblRecordCount.Text = "总计 " + table.Rows.Count.ToString() + "个记录";
            this.btnFirst.Visible = true;
            this.btnPrev.Visible = true;
            this.btnNext.Visible = true;
            this.btnLast.Visible = true;
            this.LblCurrentIndex.Visible = true;
            this.LblPageCount.Visible = true;
            this.LblRecordCount.Visible = true;
            if (table.Rows.Count == 0)
            {
                this.btnFirst.Visible = false;
                this.btnPrev.Visible = false;
                this.btnNext.Visible = false;
                this.btnLast.Visible = false;
                this.LblCurrentIndex.Visible = false;
                this.LblPageCount.Visible = false;
                this.LblRecordCount.Visible = false;
            }
            else if (this.GridView1.PageCount == 1)
            {
                this.btnFirst.Visible = false;
                this.btnPrev.Visible = false;
                this.btnNext.Visible = false;
                this.btnLast.Visible = false;
            }
            this.btnFirst.CommandName = "1";
            this.btnPrev.CommandName = (this.GridView1.PageIndex == 0) ? "1" : this.GridView1.PageIndex.ToString();
            this.btnNext.CommandName = (this.GridView1.PageCount == 1) ? this.GridView1.PageCount.ToString() : ((this.GridView1.PageIndex + 2)).ToString();
            this.btnLast.CommandName = this.GridView1.PageCount.ToString();
            this.ddlCurrentPage.Items.Clear();
            if (this.GridView1.PageCount > 0)
            {
                for (int i = 1; i <= this.GridView1.PageCount; i++)
                {
                    this.ddlCurrentPage.Items.Add(i.ToString());
                }
                this.ddlCurrentPage.SelectedIndex = this.GridView1.PageIndex;
            }
        }

        private DataTable GetExportData()
        {
            string sql = "select distinct 订单号, 送货日期,收件人,联系电话, 送货地址,产品名称,sum(pronum) as 数量, 备注,物流,物流单号 "                          
                         + " from  "
                         + " ( "
                         + " select O.ordercode as 订单号,  S.proname+'(' + convert(varchar(30),S.proprice1) +')' as 产品名称,  O.cname1 as 收件人,isnull(O.tel1,'') + ';' + isnull(phone1,'') as 联系电话, convert(varchar(10),O.senddate,111) as 送货日期, address1 as 送货地址,SendCompany as 物流,SendCode as 物流单号,[content] as 备注 ,C.pronum "
                         + " from DB_order O join DB_Car C on O.orderid = C.orderid join DB_Shoppro S on C.productid = S.proid "
                         + " where O.languages=" + info.languages("") + " ";
            sql = sql + GetSql()
                  + " ) a "
                  + " group by 订单号, 送货日期,收件人, 联系电话,送货地址,产品名称, 物流,物流单号 ,备注"
                  + " order by 送货日期 ";
        
            DataTable table = new DataTable();
            table = SQLAccess.GreatDs(sql).Tables[0];
            return table;
        }

        protected void ImageButton5_Click(object sender, ImageClickEventArgs e)
        {
            for (int i = 0; i <= (this.GridView1.Rows.Count - 1); i++)
            {
                CheckBox box = (CheckBox)this.GridView1.Rows[i].FindControl("CheckBox1");
                if (box.Checked)
                {
                    SQLAccess.DoSql("delete from DB_order where orderid=" + this.GridView1.DataKeys[i].Value + "");
                    SQLAccess.DoSql("delete from DB_car where orderid=" + this.GridView1.DataKeys[i].Value + "");
                }
            }
            base.Response.Write("<script language=javascript>alert('更新成功！');</script>");
            this.GridViewBind("");

        }

        protected void ImageButton6_Click(object sender, ImageClickEventArgs e)
        {
            string str = "0";
            for (int i = 0; i <= (this.GridView1.Rows.Count - 1); i++)
            {
                CheckBox box = (CheckBox)this.GridView1.Rows[i].FindControl("CheckBox1");
                if (box.Checked)
                {
                    str = str + "," + this.GridView1.DataKeys[i].Value;
                }
            }
            base.Response.Write("<script language=javascript>window.location.href='orderprocess.aspx';window.open('ordera.aspx?oid=" + str + "');</script>");
            base.Response.End();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            this.ImageButton5.Attributes["onclick"] = "return CheckSelect(true,'del');";
            this.ImageButton6.Attributes["onclick"] = "return CheckSelect(true,'update');";
            if (!base.IsPostBack)
            {
                base.ValidateLoginRule(ERule.OrderProcess);
                if (Request.QueryString["states"] != "")
                {
                    this.states.Value = Request.QueryString["states"];
                }
                this.BindProfessionAreaType();
                this.GridViewBind("");
              //  this.Bind();
            }
        }

        private void BindProfessionAreaType()
        {
            DataSet dsType = new DataSet();
            DALProfessionAreaType theType = new DALProfessionAreaType();
            dsType = theType.GetList("");
            if (dsType.Tables.Count > 0)
            {
                this.ddlProfessionAreaType.DataSource = dsType.Tables[0].DefaultView;
                this.ddlProfessionAreaType.DataTextField = "Name";
                this.ddlProfessionAreaType.DataValueField = "Id";
                this.ddlProfessionAreaType.DataBind();
            }
            this.ddlProfessionAreaType.Items.Insert(0, new ListItem("所属专区", ""));


        }

        protected void PagerButtonClick(object sender, EventArgs e)
        {
            this.GridView1.PageIndex = Convert.ToInt32(((LinkButton)sender).CommandName) - 1;
            this.GridViewBind("");
        }

        protected void ibtnSearch_Click(object sender, ImageClickEventArgs e)
        {
            this.GridViewBind("");
        }

        protected void ibtnExport_Click(object sender, ImageClickEventArgs e)
        {
            string fileName = DateTime.Now.ToString("yyyyMMddhhmmss") + ".csv";//设置导出文件的名称   
            DataTable dt = GetExportData();
            Gift.Utile.OperateExcel.ExportCSV(dt, fileName);
         
        }

        private string BuildExportHTML(System.Data.DataTable dt)
        {
            string result = string.Empty;
            int readCnt = dt.Rows.Count;
            int colCount = dt.Columns.Count;

            int pagerecords = 5000;
            string strTitleRow = "";
            for (int j = 0; j < colCount; j++)
            {
                strTitleRow += dt.Columns[j].ColumnName + "\t";
            }
            strTitleRow += "\r\n";

            StringBuilder strRows = new StringBuilder();
            int cnt = 1;
            for (int i = 0; i < readCnt; i++)
            {
                //strRows.Append("");
                for (int j = 0; j < colCount; j++)
                {
                    if (dt.Columns[j].DataType.Name == "DateTime" || dt.Columns[j].DataType.Name == "SmallDateTime")
                    {
                        if (dt.Rows[i][j].ToString() != string.Empty)
                        {
                            strRows.Append(Convert.ToDateTime(dt.Rows[i][j].ToString()).ToString("yyyy年MM月dd日") + "\t");
                        }
                        else
                            strRows.Append("\t");
                    }
                    else
                    {
                        strRows.Append(dt.Rows[i][j].ToString().Trim() + "\t");
                    }
                }
                strRows.Append("\r\n");
                cnt++;
                if (cnt >= pagerecords)
                {
                    result += strRows.ToString();
                    strRows.Remove(0, strRows.Length);
                    cnt = 1;
                }
            }
            result = strTitleRow + result + strRows.ToString();
            return result;
        }





        protected void ibtnInport_Click(object sender, ImageClickEventArgs e)
        {

            if (this.FileUpload1.FileContent.Length <= 0)
            {
                Response.Write("<script>alert('请选择要导入的EXCEL文件！')</script>");
                return;
            }
            else
            {
                try
                {
                    string fileName = DateTime.Now.ToString("yyyyMMddhhmmss") + ".csv";
                    this.FileUpload1.SaveAs(Server.MapPath("../uploadTempFile/" + fileName));

                    DataTable dtResult = new DataTable();
                    dtResult = Gift.Utile.OperateExcel.InputCSV(Server.MapPath("../uploadTempFile/" + fileName));

                    DataRow[] dr = dtResult.Select();
                    int ss = dtResult.Rows.Count;
                    int rowsnum = dtResult.Rows.Count;
                    if (rowsnum == 0)
                    {
                        Response.Write("<script>alert('Excel表为空表,无数据！')</script>");
                        return;
                    }
                    int iInportSum = 0;
                    for (int i = 0; i < rowsnum; i++)
                    {
                        string orderCode = dr[i][0].ToString();
                        string sendCompany = dr[i][8].ToString();
                        string sendCode = dr[i][9].ToString();

                        if (!string.IsNullOrEmpty(sendCode) || !string.IsNullOrEmpty(sendCompany))
                        {
                            string sql = "update DB_order set SendCompany = '" + sendCompany + "',SendCode='" + sendCode + "',states=2 where ordercode = '" + orderCode + "' and ( isnull(states,0)=0 or states=1)";
                            SQLAccess.DoSql(sql);
                            iInportSum++;
                        }
                        else
                        {
                            string sql = "update DB_order set states=1 where ordercode = '" + orderCode + "' and  isnull(states,0)=0";
                            SQLAccess.DoSql(sql);
                            iInportSum++;
                        }
                    }
                    Response.Write("<script>alert('成功导入" + iInportSum.ToString() + "条用户信息！')</script>");
                    this.Dispose();
                    this.GridViewBind("");
                }
                catch (Exception ex)
                {
                    Response.Write("<script>alert('请检查Excel格式是否正确！')</script>");
                    this.Dispose();
                    this.GridViewBind("");
                }
            }
        }

        protected void ibtnUpdateStates_Click(object sender, ImageClickEventArgs e)
        {
            for (int i = 0; i <= (this.GridView1.Rows.Count - 1); i++)
            {
                CheckBox box = (CheckBox)this.GridView1.Rows[i].FindControl("CheckBox1");
                if (box.Checked)
                {
                    if ((base.Request.Form["flag"].ToString() == "1") || (base.Request.Form["flag"].ToString() == "2"))
                    {
                        DataTable table = SQLAccess.GreatDs("select memberid,ordercode,orderscore,scoreprice,scoretype from DB_Order where orderid=" + this.GridView1.DataKeys[i].Value + "").Tables[0];
                        if ((table.Rows.Count > 0) && (table.Rows[0]["scoretype"].ToString() == "0"))
                        {
                            SQLAccess.DoSql(string.Concat(new object[] { "Update DB_Member set score1=score1+", Convert.ToInt32(table.Rows[0]["orderscore"]) - Convert.ToInt32(table.Rows[0]["scoreprice"]), ",score2=score2-", Convert.ToInt32(table.Rows[0]["scoreprice"]), ",score3=score3+", Convert.ToInt32(table.Rows[0]["orderscore"]), " where memberid=", table.Rows[0][0].ToString(), "" }));
                            SQLAccess.DoSql(string.Concat(new object[] { "insert into DB_Score (memberid,scorename,scoreprice,content,updatetime,scoretype) values (", table.Rows[0][0].ToString(), ",'订单赠积分：", table.Rows[0]["ordercode"], "','+", table.Rows[0]["orderscore"], "','赠积分：", table.Rows[0]["orderscore"], "','", DateTime.Now, "',0)" }));
                        }
                    }
                    SQLAccess.DoSql(string.Concat(new object[] { "Update DB_order set states=", base.Request.Form["flag"], ",scoretype=1 where orderid=", this.GridView1.DataKeys[i].Value, "" }));
                }
            }
            base.Response.Write("<script language='javascript'>alert('更新状态成功!');</script>");
            this.GridViewBind("");
        }

        protected void ibtnExport0_Click(object sender, ImageClickEventArgs e)
        {
            string fileName = DateTime.Now.ToString("yyyyMMddhhmmss") + ".xls";//设置导出文件的名称
         
            DataTable dt = GetExportDataForTemplate();
            Gift.Utile.OperateExcel.ExportCSV(dt, fileName);

        }

        private DataTable GetExportDataForTemplate()
        {
            string sql = "select top 0 '' as 订单号, "
                         + " '' as 送货日期,"
                         + " '' as 收件人,"
                         + " '' as 联系电话,"
                         + "'' as 送货地址,"
                         + " '' as 产品名称,"
                         + " '' as 数量,"
                         + " '' as 备注,"
                         + "'' as 物流,'' as 物流单号"
                         + " from DB_order O join DB_Car C on O.orderid = C.orderid join DB_Shoppro S on C.productid = S.proid";

            DataTable table = new DataTable();
            table = SQLAccess.GreatDs(sql).Tables[0];
            return table;
        }




    }
}